package com.css.fxfzypg.manage.disasterrisk.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.base.attachment.service.AttachmentInfoService;
import com.css.fxfzypg.base.exception.ServiceException;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.manage.disasterrisk.repository.DisasterRiskReqository;
import com.css.fxfzypg.manage.disasterrisk.repository.entity.DisasterRiskEntity;
import com.css.fxfzypg.manage.disasterrisk.service.DisasterRiskService;
import com.css.fxfzypg.manage.disasterrisk.verify.ExcelVerifyHandler;
import com.css.fxfzypg.manage.disasterrisk.vo.DisasterRiskParams;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

@Slf4j
@Service
public class DisasterRiskServiceImpl implements DisasterRiskService {

    @Autowired
    DisasterRiskReqository disasterRiskReqository;

    @Autowired
    AttachmentInfoService attachmentInfoService;

    @Autowired
    SysAreaService sysAreaService;

    @Autowired
    SUserService sUserService;

    @Autowired
    ExcelVerifyHandler excelVerifyHandler;

    @Autowired
    SysRoleService sysRoleService;

    /*@Override
    public Map<String, Object> checkPoint(String x,String y) {
        //标记的调研点
        Point point = new Point();
        point.setLocation(new Double(x),new Double(y));
        Map<String, Object> map = new HashMap<>();
        //获取任务表中所有任务区域
        List<FieldSurveyTaskEntity> fieldSurveyTaskEntities = disasterRiskReqository.getAllTaskRegion();
        for(int i = 0; i < fieldSurveyTaskEntities.size(); i++){
            Point[] points = new Point[i];
            FieldSurveyTaskEntity fieldSurveyTaskEntity = fieldSurveyTaskEntities.get(i);
            String taskRegion = fieldSurveyTaskEntity.getTaskRegion();
            List<Point> pointList = new ArrayList<>(Arrays.asList(points));
            for(String region : taskRegion.split(";")){
                Double regionX = new Double(region.split(",")[0].trim());
                Double regionY = new Double(region.split(",")[1].trim());
                Point regionPoint = new Point();
                regionPoint.setLocation(regionX,regionY);
                pointList.add(regionPoint);
            }
            //任务中选中的区域
            Point[] regionPointArr = pointList.toArray(points);
            //判断该灾害风险点是否在任务区域中
            boolean pointInPolygon = AreaBoundaryUtil.isPointInPolygon(point, regionPointArr);
            if(pointInPolygon){
                map.put("result","true");
                map.put("taskCode",fieldSurveyTaskEntity.getTaskNum());
                break;
            }
        }
        if(map.size() <= 0){
            map.put("result","false");
            map.put("taskCode","");
        }
        return map;
    }*/

    @Override
    public boolean saveDisasterRisk(DisasterRiskEntity disasterRiskEntity) throws UnsupportedEncodingException {
        String uuid = UUIDGenerator.getUUID();
        disasterRiskEntity.setId(uuid);
        String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(disasterRiskEntity.getProvince(), "UTF-8"), URLEncoder.encode(disasterRiskEntity.getCity(), "UTF-8"), URLEncoder.encode(disasterRiskEntity.getCounty(), "UTF-8"));
        disasterRiskEntity.setProvinceId(divisionIds.split("_")[0]);
        disasterRiskEntity.setCityId(divisionIds.split("_")[1]);
        disasterRiskEntity.setCountyId(divisionIds.split("_")[2]);
        disasterRiskEntity.setCreateTime(new Date());
        disasterRiskEntity.setIsSubmit("0");
        disasterRiskEntity.setDelFlag("0");
        String longitude = disasterRiskEntity.getLongitude();
        String latitude = disasterRiskEntity.getLatitude();
        String geom = "POINT(" + longitude + " " + latitude + ")";
        disasterRiskEntity.setGeom(geom);
        return disasterRiskReqository.saveDisasterRisk(disasterRiskEntity);
    }

    @Override
    public boolean saveAndSubmit(DisasterRiskEntity disasterRiskEntity) throws UnsupportedEncodingException {
        String uuid = UUIDGenerator.getUUID();
        disasterRiskEntity.setId(uuid);
        String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(disasterRiskEntity.getProvince(), "UTF-8"), URLEncoder.encode(disasterRiskEntity.getCity(), "UTF-8"), URLEncoder.encode(disasterRiskEntity.getCounty(), "UTF-8"));
        disasterRiskEntity.setProvinceId(divisionIds.split("_")[0]);
        disasterRiskEntity.setCityId(divisionIds.split("_")[1]);
        disasterRiskEntity.setCountyId(divisionIds.split("_")[2]);
        disasterRiskEntity.setIsSubmit("1");
        disasterRiskEntity.setDelFlag("0");
        disasterRiskEntity.setCreateTime(new Date());
        disasterRiskEntity.setSubmitter(disasterRiskEntity.getCreateName());
        disasterRiskEntity.setSubmitterId(disasterRiskEntity.getCreateId());
        disasterRiskEntity.setSubmitTime(new Date());
        String longitude = disasterRiskEntity.getLongitude();
        String latitude = disasterRiskEntity.getLatitude();
        String geom = "POINT(" + longitude + " " + latitude + ")";
        disasterRiskEntity.setGeom(geom);
        return disasterRiskReqository.saveDisasterRisk(disasterRiskEntity);
    }


    @Override
    public Map<String, Object> querySubmitOrNot(String submitFlag, int curPage, int pageSize, String userId) {
        Map<String, Object> map = disasterRiskReqository.querySubmitOrNot(submitFlag, curPage, pageSize, userId);
        return map;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateIsSubmit(Map<String, String> map) {
        return disasterRiskReqository.updateIsSubmit(map);
    }

    @Override
    public DisasterRiskEntity queryData(String id) {
        DisasterRiskEntity disasterRiskEntity = disasterRiskReqository.queryData(id);
        return disasterRiskEntity;
    }

    @Override
    public boolean modifyData(DisasterRiskEntity disasterRiskEntity) {
        return disasterRiskReqository.modifyData(disasterRiskEntity);
    }

    @Override
    public boolean modifyAndSubmit(DisasterRiskEntity disasterRiskEntity) {
        disasterRiskEntity.setIsSubmit("1");
        disasterRiskEntity.setSubmitter(disasterRiskEntity.getCreateName());
        disasterRiskEntity.setSubmitterId(disasterRiskEntity.getCreateId());
        disasterRiskEntity.setSubmitTime(new Date());
        return disasterRiskReqository.modifyData(disasterRiskEntity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteDisasterRisk(String ids) {
        boolean res = true;
        for (String id : ids.split(",")) {
            res = disasterRiskReqository.deleteDisasterRisk(id);
            if (res == false) {
                break;
            }
        }
        return res;
    }


    @Override
    public Map<String, Object> queryDisasterData(DisasterRiskParams queryParams, int curPage, int pageSize) {
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> maps = JSONObject.parseArray(role, Map.class);//一个人可能有多个角色
        //当前登录人所有的角色
        StringBuilder roles = new StringBuilder();
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode") + ",");
        }
        String allRole = roles.toString();
        String provinceId = sUser.getProvinceId();//省id
        if (allRole.contains(FxfzConstants.YPG_COUN_GL_ROLE)||allRole.contains(FxfzConstants.YPG_COUN_YW_ROLE)) {
            Map<String, Object> map = disasterRiskReqository.queryDisasterData(queryParams, curPage, pageSize);
            return map;
        }else if (allRole.contains(FxfzConstants.YPG_PRI_GL_ROLE)||allRole.contains(FxfzConstants.YPG_PRI_YW_ROLE)){
            Map<String, Object> map = disasterRiskReqository.queryDisasterDataByProvinceId(queryParams, curPage, pageSize,provinceId);
            return map;
        }else {
            return null;
        }


    }

    @Override
    public List<DisasterRiskEntity> queryDisasterDataMap() {
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> maps = JSONObject.parseArray(role, Map.class);//一个人可能有多个角色
        //当前登录人所有的角色
        StringBuilder roles = new StringBuilder();
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode") + ",");
        }
        String allRole = roles.toString();
        String provinceId = sUser.getProvinceId();//省id
        if (allRole.contains(FxfzConstants.YPG_COUN_GL_ROLE)||allRole.contains(FxfzConstants.YPG_COUN_YW_ROLE)){
            return disasterRiskReqository.queryDisasterDataMap();
        }else if (allRole.contains(FxfzConstants.YPG_PRI_GL_ROLE)||allRole.contains(FxfzConstants.YPG_PRI_YW_ROLE)){
            return disasterRiskReqository.queryDisasterDataMapByProvinceId(provinceId);
        }else {
            return null;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> uploadDisasterRisk(MultipartFile file) throws Exception {
        ImportParams params = new ImportParams();
        params.setImportFields(new String[]{"*灾害风险点名称", "*灾害风险点位置-省", "*灾害风险点位置-市", "*灾害风险点位置-区/县", "*灾害风险点位置-详细地址", "*经度", "*纬度", "*灾害风险类型", "*灾害风险点描述"});
        params.setNeedVerify(true);
        params.setVerifyHandler(excelVerifyHandler);
        boolean res = false;
        Map<String, Object> map = new HashMap<>();
        try {
            String userId = PlatformSessionContext.getUserID();
            String user = sUserService.getSUser(userId);
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            String userName = sUser.getUserName();
            InputStream inputStream = file.getInputStream();
            ExcelImportResult<DisasterRiskEntity> result = ExcelImportUtil.importExcelMore(inputStream, DisasterRiskEntity.class, params);
            List<DisasterRiskEntity> failList = result.getFailList();
            if (PlatformObjectUtils.isNotEmpty(failList)) {
                StringBuilder errorMsg = new StringBuilder("<font size='5px' color='red'>导入失败：</font>");
                for (DisasterRiskEntity hisPrEntity : failList) {
                    errorMsg.append("<font size='4px' ><br>").append("第").append(hisPrEntity.getRowNum() + 1).append("行： ").append(hisPrEntity.getErrorMsg()).append("</font>");
                }
                map.put("res", res);
                map.put("mess", errorMsg);
                return map;
            }
            List<DisasterRiskEntity> resultData = result.getList();//解析excel
            if (PlatformObjectUtils.isNotEmpty(resultData)) {
                List<DisasterRiskEntity> list = new ArrayList<>();
                int excelReadRowIndex = 1;
                for (DisasterRiskEntity disasterRiskEntity : resultData) {
                    if (PlatformObjectUtils.isEmpty(disasterRiskEntity.getDisasterName()) && PlatformObjectUtils.isEmpty(disasterRiskEntity.getProvince()) && PlatformObjectUtils.isEmpty(disasterRiskEntity.getCity()) && PlatformObjectUtils.isEmpty(disasterRiskEntity.getCounty()) && PlatformObjectUtils.isEmpty(disasterRiskEntity.getDisasterName())) {
                        continue;
                    }
                    String uuid = UUIDGenerator.getUUID();
                    disasterRiskEntity.setId(uuid);
                    String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(disasterRiskEntity.getProvince(), "UTF-8"), URLEncoder.encode(disasterRiskEntity.getCity(), "UTF-8"), URLEncoder.encode(disasterRiskEntity.getCounty(), "UTF-8"));
                    if (StringUtils.isBlank(divisionIds)) {
                        throw new ServiceException("第" + excelReadRowIndex + "行的建筑地点-省(" + disasterRiskEntity.getProvince().trim() + ")有误，请填写准确的名称，例如：北京市");
                    }
                    disasterRiskEntity.setProvinceId(divisionIds.split("_")[0]);
                    if (divisionIds.split("_").length == 1) {
                        throw new ServiceException("第" + excelReadRowIndex + "行的建筑地点-市(" + disasterRiskEntity.getCity().trim() + ")有误，请填写准确的名称，例如：北京市");
                    }
                    disasterRiskEntity.setCityId(divisionIds.split("_")[1]);
                    if (divisionIds.split("_").length == 2) {
                        throw new ServiceException("第" + excelReadRowIndex + "行的建筑地点-县(" + disasterRiskEntity.getCounty().trim() + ")有误，请填写准确的名称，例如：北京市");
                    }
                    //                    disasterRiskEntity.setProvinceId(divisionIds.split("_")[0]);
//                    disasterRiskEntity.setCityId(divisionIds.split("_")[1]);
                    disasterRiskEntity.setCountyId(divisionIds.split("_")[2]);
                    String disasterType = disasterRiskEntity.getDisasterType();
                    StringBuilder stringBuilder = new StringBuilder();
                    String disasterTypeStr = "";
                    for (String type : disasterType.split(",")) {
                        if (type.equals("滑坡")) {
                            stringBuilder.append("hp,");
                        } else if (type.equals("崩塌")) {
                            stringBuilder.append("bt,");
                        } else if (type.equals("火灾")) {
                            stringBuilder.append("hz,");
                        } else if (type.equals("道路拥堵/中断")) {
                            stringBuilder.append("dlyd,");
                        } else if (type.equals("危险品泄露")) {
                            stringBuilder.append("wxpxl,");
                        } else if (type.equals("其他")) {
                            stringBuilder.append("qt,");
                        }
                    }
                    if (PlatformObjectUtils.isNotEmpty(stringBuilder.toString())) {
                        disasterTypeStr = stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1);
                        disasterRiskEntity.setDisasterType(disasterTypeStr);
                    }
                    disasterRiskEntity.setIsSubmit("1");
                    disasterRiskEntity.setDelFlag("0");
                    disasterRiskEntity.setCreateName(userName);
                    disasterRiskEntity.setCreateId(userId);
                    disasterRiskEntity.setCreateTime(new Date());
                    disasterRiskEntity.setSubmitter(userName);
                    disasterRiskEntity.setSubmitterId(userId);
                    disasterRiskEntity.setSubmitTime(new Date());
                    String longitude = disasterRiskEntity.getLongitude();
                    String latitude = disasterRiskEntity.getLatitude();
                    String geom = "POINT(" + longitude + " " + latitude + ")";
                    disasterRiskEntity.setGeom(geom);
                    list.add(disasterRiskEntity);
                }
                if (!PlatformObjectUtils.isEmpty(list)) {
                    for (DisasterRiskEntity entity : list) {
                        res = disasterRiskReqository.saveDisasterRisk(entity);//保存
                        if (!res) {
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            if (e.getMessage().contains("不是合法")) {
                map.put("mess", "上传失败! 上传的文件模板有误,请检查表头是否改动！");
            }
            throw e;
        }
        map.put("res", res);
        return map;
    }

    @Override
    public void exportDisasterRisk(HttpServletResponse response, DisasterRiskParams queryParams) {
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> maps = JSONObject.parseArray(role, Map.class);//一个人可能有多个角色
        //当前登录人所有的角色
        StringBuilder roles = new StringBuilder();
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode") + ",");
        }
        String allRole = roles.toString();
        String provinceId = sUser.getProvinceId();//省id
        List<DisasterRiskEntity> disasterRiskEntities = new ArrayList<>();
        if (allRole.contains(FxfzConstants.YPG_COUN_GL_ROLE)||allRole.contains(FxfzConstants.YPG_COUN_YW_ROLE)) {
            disasterRiskEntities =  disasterRiskReqository.queryDisaster(queryParams);
        }else if (allRole.contains(FxfzConstants.YPG_PRI_GL_ROLE)||allRole.contains(FxfzConstants.YPG_PRI_YW_ROLE)){
            disasterRiskEntities = disasterRiskReqository.queryDisasterDataByProvinceId(queryParams, provinceId);
        }


        if (disasterRiskEntities == null || disasterRiskEntities.size() <= 0) {
            throw new RuntimeException("数据为空,无法导出！");
        }
        try {
            List<DisasterRiskEntity> list = new ArrayList<>();
            for (DisasterRiskEntity disasterRiskEntity : disasterRiskEntities) {
                String disasterType = disasterRiskEntity.getDisasterType();
                StringBuilder stringBuilder = new StringBuilder();
                for (String type : disasterType.split(",")) {
                    if (type.equals("hp")) {
                        stringBuilder.append("滑坡、");
                    } else if (type.equals("bt")) {
                        stringBuilder.append("崩塌、");
                    } else if (type.equals("hz")) {
                        stringBuilder.append("火灾、");
                    } else if (type.equals("dlyd")) {
                        stringBuilder.append("道路拥堵/中断、");
                    } else if (type.equals("wxpxl")) {
                        stringBuilder.append("危险品泄露、");
                    } else if (type.equals("qt")) {
                        stringBuilder.append("其他、");
                    }else{
                        stringBuilder.append(type).append("、");
                    }
                }
                try{
                    String disasterTypeStr = stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1);
                    disasterRiskEntity.setDisasterType(disasterTypeStr);
                    list.add(disasterRiskEntity);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
            EasyPoiExcelUtil.exportExcel(list, null, "sheet", DisasterRiskEntity.class, "灾害风险点信息模板", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
